 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShivamEMR.Model.Domain.PatientDomain;
using ShivamEMR.Model.DataInterfaces.PersonDataInterf;
using ShivamEMR.Model.DataInterfaces.CompanyDataInterf;
using ShivamEMR.Model.DataInterfaces.PatientDataInterf;
using ShivamEMR.Model;
using PagedList;
using System.IO;
using ShivamEMR.Model.Domain.ContactsDomain;
using ShivamEMR.Model.DataInterfaces.ContactsDataInterf;
using ShivamEMR.Web.Areas.Patient.ViewModels;
using ShivamEMR.Web.Models;

namespace ShivamEMR.Web.Areas.Patient.Controllers
{   
    public class PatientController : Controller
    {
		private readonly ISexRepository sexRepository;
		private readonly IPersonPictureRepository personpictureRepository;
		private readonly IPersonAccountRepository personaccountRepository;
		private readonly IPersonStatusRepository personstatusRepository;
		private readonly IBranchRepository branchRepository;
		private readonly IPatientRepository patientRepository;
        private readonly IMaritalStatusRepository maritalstatusRepo;
        private readonly IContactRepository contactRepository;


		// If you are using Dependency Injection, you can delete the following constructor
        #region Constructors
        public PatientController()
        {
            sexRepository = Registry.RepositoryFactory.GetSexRepository();
            personpictureRepository = Registry.RepositoryFactory.GetPersonPictureRepository();
            personstatusRepository = Registry.RepositoryFactory.GetPersonStatusRepository();
            branchRepository = Registry.RepositoryFactory.GetBranchRepository();
            patientRepository = Registry.RepositoryFactory.GetPatientRepository();
            maritalstatusRepo = Registry.RepositoryFactory.GetMaritalStatusRepository();
            contactRepository = Registry.RepositoryFactory.GetContactRepository();
        }

        public PatientController(ISexRepository sexRepository, IPersonPictureRepository personpictureRepository, IPersonAccountRepository personaccountRepository, IPersonStatusRepository personstatusRepository, IBranchRepository branchRepository, IPatientRepository patientRepository, IMaritalStatusRepository maritalstatusrepo, IContactRepository contactrepo)
        {
            this.sexRepository = sexRepository;
            this.personpictureRepository = personpictureRepository;
            this.personaccountRepository = personaccountRepository;
            this.personstatusRepository = personstatusRepository;
            this.branchRepository = branchRepository;
            this.patientRepository = patientRepository;
            this.maritalstatusRepo = maritalstatusrepo;
            this.contactRepository = contactrepo;
        }
        
        #endregion
        //
        // GET: /Patient/

        public ViewResult Index()
        {
            var patients = patientRepository.All;
            //if (!String.IsNullOrEmpty(searchString))
            //{
            //    patients = patients.Where(p => p.FirstName.ToUpper().Contains(searchString.ToUpper())
            //                       || p.MiddleName.ToUpper().Contains(searchString.ToUpper())
            //                       || p.LastName.ToUpper().Contains(searchString.ToUpper())
            //        || p.Code.ToUpper().Contains(searchString.ToUpper()) );
            //}
            //var plist = patients.ToList<ShivamEMR.Model.Domain.PatientDomain.Patient>();
            //int pageSize = 10;
            //int pageNumber = (page ?? 1);
            return View(patients);         
           // return View(patientRepository.All);//Including(patient => patient.Sex, patient => patient.Picture, patient => patient.PersonStatus, patient => patient.Addresses, patient => patient.Contacts, patient => patient.CitizenShips, patient => patient.Informations, patient => patient.PersonRoles, patient => patient.Groups, patient => patient.Documents, patient => patient.Assignments, patient => patient.InteractionsWith, patient => patient.RegisteredInBranch, patient => patient.PatientGroups, patient => patient.PatientInformations, patient => patient.Treatments, patient => patient.Consultations, patient => patient.Admissions, patient => patient.Diagnostics, patient => patient.Tests, patient => patient.Representatives, patient => patient.Insurances));
        }

        public string Upload(HttpPostedFileBase fileData)
        {

            //Add into folder
            var fileName = this.Server.MapPath("/Uploads/" + System.IO.Path.GetFileName(fileData.FileName));
            fileData.SaveAs(fileName);

            return Path.GetFileName(fileName);
        }
        public ViewResult PDashboard(System.Guid id)
        {
            return View(patientRepository.Find(id));
        }
        //
        // GET: /Patient/Details/5

        public ViewResult DoctorDashboard(Guid id)
        {
            return View(patientRepository.Find(id));
        }

        public ViewResult EmployeeDashboard(Guid id)
        {
            return View(patientRepository.Find(id));
        }

        public ViewResult Details(System.Guid id)
        {
            return View(patientRepository.Find(id));
        }

        

        public ActionResult NewContact()
        {
            ViewBag.PossibleContactTypes = Registry.RepositoryFactory.GetContactTypeRepository().All;
            return PartialView();
        }

        [HttpPost]
        public ActionResult NewContact(Contact contact)
        {
            if (ModelState.IsValid)
            {
              if(Session["patient"]!=null){
                  var patient = ((ShivamEMR.Model.Domain.PatientDomain.Patient)Session["patient"]);
                  if (patient.Contacts == null)
                      patient.Contacts = new List<Contact>();
                  patient.Contacts.Add(contact);
              }
                
               return Content(Boolean.TrueString);
             // return Json(JsonResponseFactory.SuccessResponse(contact), JsonRequestBehavior.DenyGet);
            }
            else
            {
             return Content("Please review your form");
               // return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }




        public ActionResult NewAddress()
        {
            ViewBag.PossibleAddressTypes = Registry.RepositoryFactory.GetAddressTypeRepository().All;
            ViewBag.PassibleCities = Registry.RepositoryFactory.GetCityRepository().All;
            ViewBag.PassibleTerritories= Registry.RepositoryFactory.GetTerritoryRepository().All;
            ViewBag.PassibleCountries= Registry.RepositoryFactory.GetCountryRepository().All;
          
            return PartialView();
        }

        [HttpPost]
        public JsonResult NewAddress(Address address)
        {
            if (ModelState.IsValid)
            {
                if (Session["patient"] != null)
                {
                    var patient = ((ShivamEMR.Model.Domain.PatientDomain.Patient)Session["patient"]);
                    if (patient.Addresses == null)
                        patient.Addresses = new List<Address>();
                    patient.Addresses.Add(address);
                }

                return Json(JsonResponseFactory.SuccessResponse(address), JsonRequestBehavior.DenyGet);
            }
            else
            {
                return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult NewPatientInformation()
        {           
            return PartialView();
        }

        [HttpPost]
        public JsonResult NewPatientInformation(PatientInformation pinfo)
        {
            if (ModelState.IsValid)
            {
                if (Session["patient"] != null)
                {
                    var patient = ((ShivamEMR.Model.Domain.PatientDomain.Patient)Session["patient"]);
                    if (patient.PatientInformations == null)
                        patient.PatientInformations = new List<PatientInformation>();
                    patient.PatientInformations.Add(pinfo);
                }

                return Json(JsonResponseFactory.SuccessResponse(pinfo), JsonRequestBehavior.DenyGet);
            }
            else
            {
                return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }

        public ActionResult NewRepresentative()
        {
            return PartialView();
        }

        [HttpPost]
        public JsonResult NewRepresentative(PatientRepresentative representative)
        {
            if (ModelState.IsValid)
            {
                if (Session["patient"] != null)
                {
                    var patient = ((ShivamEMR.Model.Domain.PatientDomain.Patient)Session["patient"]);
                    if (patient.Representatives == null)
                        patient.Representatives = new List<PatientRepresentative>();
                    patient.Representatives.Add(representative);
                }

                return Json(JsonResponseFactory.SuccessResponse(representative), JsonRequestBehavior.DenyGet);
            }
            else
            {
                return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
            }
        }
        //
        // GET: /Patient/Create

        public ActionResult Create()
        {
			ViewBag.PossibleSexes = sexRepository.All;
			ViewBag.PossiblePictures = personpictureRepository.All;
			ViewBag.PossiblePersonAccounts = personaccountRepository.All;
			ViewBag.PossiblePersonStatus = personstatusRepository.All;
			ViewBag.PossibleRegisteredInBranches = branchRepository.All;
            ViewBag.PossibleMaritalStatus = maritalstatusRepo.All;
        var patient = new  ShivamEMR.Model.Domain.PatientDomain.Patient() { DateOfBirth=DateTime.Now,RegistrationDate=DateTime.Now  };
        patient.Contacts = new List<Contact>();
        patient.Addresses = new List<Address>();
        patient.PatientInformations = new List<PatientInformation>();
        patient.Representatives = new List<PatientRepresentative>();
        Session["patient"] = patient;
            return View(patient);
        } 

        //
        // POST: /Patient/Create

        [HttpPost]
        public ActionResult Create(ShivamEMR.Model.Domain.PatientDomain.Patient patient)
        {
            if (ModelState.IsValid) {
                patientRepository.Update(patient);
                patientRepository.Save();
                return RedirectToAction("Index");
            } else {
				ViewBag.PossibleSexes = sexRepository.All;
				ViewBag.PossiblePictures = personpictureRepository.All;
				ViewBag.PossiblePersonAccounts = personaccountRepository.All;
				ViewBag.PossiblePersonStatus = personstatusRepository.All;
				ViewBag.PossibleRegisteredInBranches = branchRepository.All;
                ViewBag.PossibleMaritalStatus = maritalstatusRepo.All;
                if(patient==null)
                 patient = new ShivamEMR.Model.Domain.PatientDomain.Patient() { DateOfBirth = DateTime.Now, RegistrationDate = DateTime.Now };
				return View(patient);
			}
        }
        
        //
        // GET: /Patient/Edit/5
 
        public ActionResult Edit(System.Guid id)
        {
			ViewBag.PossibleSexes = sexRepository.All;
			ViewBag.PossiblePictures = personpictureRepository.All;
			ViewBag.PossiblePersonAccounts = personaccountRepository.All;
			ViewBag.PossiblePersonStatus = personstatusRepository.All;
			ViewBag.PossibleRegisteredInBranches = branchRepository.All;
            ViewBag.PossibleMaritalStatus = maritalstatusRepo.All;
             return View(patientRepository.Find(id));
        }

        //
        // POST: /Patient/Edit/5

        [HttpPost]
        public ActionResult Edit(ShivamEMR.Model.Domain.PatientDomain.Patient patient)
        {
            if (ModelState.IsValid) {
                patientRepository.InsertOrUpdate(patient);
                patientRepository.Save();
                return RedirectToAction("Index");
            } else {
				ViewBag.PossibleSexes = sexRepository.All;
				ViewBag.PossiblePictures = personpictureRepository.All;
				ViewBag.PossiblePersonAccounts = personaccountRepository.All;
				ViewBag.PossiblePersonStatus = personstatusRepository.All;
				ViewBag.PossibleRegisteredInBranches = branchRepository.All;
                ViewBag.PossibleMaritalStatus = maritalstatusRepo.All;
				return View();
			}
        }

        //
        // GET: /Patient/Delete/5
 
        public ActionResult Delete(System.Guid id)
        {
            return View(patientRepository.Find(id));
        }

        //
        // POST: /Patient/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(System.Guid id)
        {
            var p = patientRepository.Find(id);
            patientRepository.Delete(p);
            patientRepository.Save();

            return RedirectToAction("Index");
        }
    }
}

